//调用router

use super::router::Router;
use http::httprequest::HttpRequest;
use std::io::prelude::*;
use std::net::TcpListener;
use std::str;

//成员有& 则此结构体需要 声明周期
pub struct Server<'a>{
    socket_addr:&'a str,
}

impl<'a> Server<'a>{
    //Self 可以写成 Server
    pub fn new(socket_addr:&'a str)->Self{
        Server{socket_addr}
    }
    //运行server
    pub fn run(&self){
        let connection_listener=TcpListener::bind(self.socket_addr).unwrap();
        println!("Running on {}",self.socket_addr);

        for stream in connection_listener.incoming(){
            let mut stream=stream.unwrap();
            println!("connect established");
            let mut read_buf=[0;1024];
            stream.read(&mut read_buf).unwrap();
            //from_utf8 将字节数组转换为字符串
            //String-》HttpRequest 已经实现了 可以into转化
            let req:HttpRequest=String::from_utf8(read_buf.to_vec()).unwrap().into();
            //路由将数据分发给不同的handler 处理
            Router::router(req,&mut stream);
        }
    }
}